




//
//  ZNetworkService.m
//  ZQLearn
//
//  Created by admin on 2019/4/16.
//  Copyright © 2019 admin. All rights reserved.
//

#import "ZNetworkService.h"
#import "Z_API.h"
#import "Z_HTTPServer.h"
//#import "NSString+MD5.h"

static  NSString *GETMethod = @"get";
static NSString *netFailTips = @"亲,您的网络开小差了";
#define kTimeout 15

static  AFHTTPSessionManager *manager;

@interface ZNetworkService()
{
    NSURLSessionDownloadTask *_downloadTask;
}

@end

@implementation ZNetworkService

/**
 *  对AFHTTPSessionManager启用单例模式
 *
 *  @return 单例
 */
+ (AFHTTPSessionManager*)sharedManager{
    
    static ZNetworkService* sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc]init];
        manager = [AFHTTPSessionManager manager];
        //申明返回的结果是json类型
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        //如果后台需要我们给他传json格式数据就这样传  测试中
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        
        //正常的是这样传，直接用一个参数字典
        //        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        manager.requestSerializer.timeoutInterval = kTimeout;
        //        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/javascript",@"application/json",@"text/html", nil];
        
    });
    return manager;
}
#pragma mark - get 请求

///get请求
+(void)getRequestWithBaseUrl:(NSString *__nonnull)url setParameters:(NSDictionary *__nonnull)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail delegater:(UIView *)view
{
    NSError *error;
    if (!url) {
        fail(error);
        return;
    }
//    [SVProgressHUD show];
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",HTTP_BASE,url];
    YYLog(@"打印当前接口%@",requestUrl);
    [self getRequestWithUrl:requestUrl setParameters:paraDic success:^(id result) {
        if (success) {
            success(result);
//            [SVProgressHUD dismiss];
        }
        
    } fail:^(NSError *error) {
        
        fail(error);
//        [SVProgressHUD dismiss];
        
    } delegater:view];
    
}

///被基类方法调用
+(void)getRequestWithUrl:(NSString *__nonnull)url setParameters:(NSDictionary *__nonnull)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail delegater:(UIView *)view
{
    
    if (view) {
        //        [MBProgressHUD showHUDAddedTo:view animated:YES];
        //        [SVProgressHUD show];
    }
    
    AFHTTPSessionManager *manager = [self sharedManager];
    
    //这种写法也没问题，说明请求时候不用做序列化操作 但是那个资料修改页面除外那个待测试
    ////这块需要后续修改一下
    if ([UserModel shareInstance].isCart==YES) {
         manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }else{
         manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
    //    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    ///经过测试，请求时候AFHTTPRequestSerializer  这个可以不设置，应该是afnet直接帮助做了默认设置，
   
    ///这个对于请求响应的序列是需要写的，如果是http 的话返回的是一串子 二进制
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/javascript",@"application/json",@"text/html", nil];
    
    manager.requestSerializer.timeoutInterval = kTimeout;
    
    //如果有内嵌证书的话需要这里选择其他模式
    AFSecurityPolicy * securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    
    //    如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    manager.securityPolicy = securityPolicy;
    [manager GET:url parameters:paraDic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable result) {
        //因为是异步所以会延迟一下才显示出来
        if (success) {
            
            success(result);
            //[MBProgressHUD hideHUDForView:view animated:YES];
            //            [SVProgressHUD dismiss];
        }
        
        //        YYLog(@"%@",result);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        YYLog(@"fail");
        fail(error);
        if (view) {
            
            //    [MBProgressHUD hideHUDForView:view animated:YES];
            //            [SVProgressHUD dismiss];
        }
    }];
    
}



#pragma mark - post 请求
///post请求  基类
+(void)postRequestWithBaseUrl:(NSString *__nonnull)url setParameters:(NSDictionary *__nonnull)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail delegater:(UIView *)view
{
    NSError *error;
    if (!url) {
        fail(error);
        return;
    }
//    [SVProgressHUD show];
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",HTTP_BASE,url];
    YYLog(@"当前接口：%@",requestUrl);
    [self postRequestWithUrl:requestUrl setParameters:paraDic success:^(id result) {
        
        if ([result isKindOfClass:[NSData class]]) {
            
            YYLog(@"%@",result);
            //后台返回的是序列串  是json 序列串
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableLeaves error:nil];
            YYLog(@"8899%@",dict);
            
            if (success) {
                
                success(dict);
//                  [SVProgressHUD dismiss];
                //                success(result);
            }
            
        }else{
            
            if (success) {
                
                success(result);
//                [SVProgressHUD dismiss];
            }
        }
    } fail:^(NSError *error) {
        
        fail(error);
        YYLog(@"%@",error);
//        [SVProgressHUD dismiss];
    } delegater:view];
    
}

#warning 这块请求头的设置需要进行优化

///后续测试数据请求这块
//    if ([NUserModel shareInstance].isDifferentRequest) {
//
//        ///这个是一个例外  其他接口都是下面的方式
//        manager.requestSerializer = [AFJSONRequestSerializer serializer];
//        manager.responseSerializer = [AFJSONResponseSerializer serializer];
//
//    }else{
//
//        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//        manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    }


//application/x-www-form-urlencoded   我们发送的一个http请求都是这种方式

//application/json 这种是afnet 默认的 所以如果后台需要json 格式的数据的话  就不用设置这个了，当然设置了也没关系
///被基类方法调用
+(void)postRequestWithUrl:(NSString *__nonnull)url setParameters:(NSDictionary *__nonnull)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail delegater:(UIView *)view
{
    if (view) {
        
    }
    //单例初始化一次，防止内存问题
    //    AFHTTPSessionManager *manager = [self sharedManager];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
#warning 227这行代码很重要 可以对比南宁云的请求基础类里面的相关解释
    ///**********************这句代码
    if ([UserModel shareInstance].isLogin) {
        ///登录时候用的是json 数据   post
         manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }else{
        //资讯和一般的post请求用的数据提交方式  用的是正常的post形式
         manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    manager.requestSerializer.timeoutInterval = kTimeout;
    [manager POST:url parameters:paraDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable result) {
        
        if (success) {
            
            success(result);
            dispatch_async(dispatch_get_main_queue(), ^{
                //[SVProgressHUD dismiss];
                
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
        if (view) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //                [SVProgressHUD dismiss];
                //                [PTSProgressHUD hide];
            });
        }
    }];
}


#pragma mark - 图片上传

//图片上传
+(void)uploadImage:(UIImage *)image url:(NSString *)urlString{
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",HTTP_BASE,urlString];
    
    AFHTTPSessionManager *manager = [self sharedManager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //上传图片/文字，POST
    
    //    NSString *userId = [WDUserInfoModel shareInstance].memberId;
    //
    //使用时需要把参数补齐
    NSDictionary *commanDic;
    
    //    = @{@"ai.cc":CHANNEL,@"ai.cp":@"6C07A7D7C49F0E3FE692B5FF66715086",@"bi.ct":[ToolClass getIDFA],@"bi.dv":@"IOS",@"bi.mi":userId?userId:@""};
    
    NSDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:commanDic];
    
    
    [manager POST:requestUrl parameters:dic constructingBodyWithBlock:^(id  _Nonnull formData) {
        //对于图片进行压缩
        NSData *data = UIImageJPEGRepresentation(image, 0.1);
        //第一个代表文件转换后data数据，第二个代表图片的名字，第三个代表图片放入文件夹的名字，第四个代表文件的类型
        [formData appendPartWithFileData:data name:@"1" fileName:@"image.jpg" mimeType:@"image/jpg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        YYLog(@"uploadProgress = %@",uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable result) {
        
        NSDictionary * obj = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
        YYLog(@"%@",obj);
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        YYLog(@"error = %@",error);
    }];
}


///文件方式上传图片

+(void)uploadImage:(NSArray *)photos url:(NSString *)urlString parameters:(NSDictionary *)paraDic success:(void (^)(id))success fail:(void (^)(NSError *))fail delegater:(UIView *)view{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet
                                                         setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    YYLog(@"%@",photos);
    [manager POST:urlString parameters:paraDic constructingBodyWithBlock:^(id  _Nonnull formData) {
        
        //对于图片进行压缩
        //        NSData *data = UIImageJPEGRepresentation(image, 0.1);
        //第一个代表文件转换后data数据，第二个代表图片的名字，第三个代表图片放入文件夹的名字，第四个代表文件的类型
        //        [formData appendPartWithFileData:data name:@"1" fileName:@"image.jpg" mimeType:@"image/jpg"];
        for (int i = 0; i < photos.count; i++) {
            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
            formatter.dateFormat=@"yyyyMMddHHmmss";
            NSString *str=[formatter stringFromDate:[NSDate date]];
            NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
            UIImage *image = photos[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.28);
            
            //后台规定名称必须是file
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg"];
            
            
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        YYLog(@"uploadProgress = %@",uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable result) {
        
        NSDictionary * obj = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
        YYLog(@"%@",obj);
        success(obj);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        YYLog(@"error = %@",error);
        
    }];
    
}

+(NSInteger)getStatusCodeWithObj:(NSDictionary *)dic{
    NSString *code = dic[@"code"];
    return [code integerValue];
}



@end
